<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
  <title>用户列表</title>
  <div th:replace="common/link::header"></div>
</head>
<body>
  <div class="layui-fluid">
    <div class="layui-row layui-col-space15">
      <!-- 左树 -->
      <div class="layui-col-sm12 layui-col-md3 layui-col-lg3">
        <div class="layui-card" style="height: 100%">
          <div class="layui-card-header layuiadmin-card-header-auto">
            部门
          </div>
          <div class="layui-card-body mini-bar">
            <div id="deptTree" class="ztree"></div>
          </div>
        </div>
      </div>
      <!-- 右表 -->
      <div class="layui-col-sm12 layui-col-md9 layui-col-lg9">
        <div class="layui-card">
          <form class="layui-form layui-card-header layuiadmin-card-header-auto">
            <input type="hidden" name="deptId" id="deptId">
            <div class="layui-form-item">
              <div class="layui-inline">
                <label class="layui-form-label">昵称</label>
                <div class="layui-input-block">
                  <input type="text" name="nickName" placeholder="请输入昵称" class="layui-input">
                </div>
              </div>
              <div class="layui-inline">
                <label class="layui-form-label">手机号</label>
                <div class="layui-input-block">
                  <input type="text" name="phonenumber" placeholder="请输入手机号" class="layui-input">
                </div>
              </div>
              <div class="layui-inline">
                <button type="button" class="layui-btn layuiadmin-btn-useradmin" lay-submit lay-filter="search">
                  <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                </button>
                <button type="reset" class="layui-btn layui-btn-primary" lay-submit lay-filter="reset">重置</button>
              </div>
            </div>
          </form>
          <div class="layui-card-body">
            <table id="userTable" lay-filter="userTable"></table>
            <script type="text/html" id="toolbar">
              <div class="layui-btn-container">
                <a class="layui-btn layui-btn-xs" lay-event="export"><i class="layui-icon layui-icon-file"></i>导出</a>
                <a sec:authorize="hasAuthority('user:add')" class="layui-btn layui-btn-xs" lay-event="add"><i class="layui-icon layui-icon-add-1"></i>添加</a>
                <a sec:authorize="hasAuthority('user:del')" class="layui-btn layui-btn-danger layui-btn-xs" lay-event="removes"><i class="layui-icon layui-icon-delete"></i>删除</a>
              </div>
            </script>
            <script type="text/html" id="enabledTpl">
              {{#  if(d.userName != 'admin'){ }}
                <input type="checkbox" lay-filter="enabled" value="{{d.id}}" lay-skin="switch" lay-text="激活|冻结" {{d.enabled==='Y'?'checked':''}} />
              {{#  } }}
            </script>
            <script type="text/html" id="tableBar">
              {{#  if(d.userName != 'admin'){ }}
                <a sec:authorize="hasAuthority('user:pass')" class="layui-btn layui-btn-danger layui-btn-xs" lay-event="pass"><i class="layui-icon layui-icon-password"></i>重置</a>
                <a sec:authorize="hasAuthority('user:edit')" class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
                <a sec:authorize="hasAuthority('user:del')" class="layui-btn layui-btn-danger layui-btn-xs" lay-event="remove"><i class="layui-icon layui-icon-delete"></i>删除</a>
              {{#  } }}
            </script>
          </div>
        </div>
      </div>
  </div>
<div th:replace="common/script::footer"></div>
<script th:inline="javascript">
  layui.config({
      base: '/static/layuiadmin/' //静态资源所在路径
  }).extend({
    index: 'lib/index', //主入口模块
  }).use(['index', 'useradmin', 'table','crud'], function() {
      let $ = layui.$,
              form = layui.form,
              crud = layui.crud,
              table = layui.table;
       // 左侧树结构
       $.ajax({
        type: "get",
        url:  ctx + '/system/sysDept/treeSelect',
        success: function(data) {
          let zTree = $.fn.zTree.init($("#deptTree"), fun.setting(function (event,treeId,treeNode) {
            let deptIds = fun.getzTreeChildrenNodeIds(treeNode);
            //执行重载
            table.reload('userTable', {
              where: {
                deptIds
              }
            });
          }), data);
          zTree.expandAll(true);
        }
      });
      //监听搜索
      form.on('submit(search)', function(data) {
        let field = data.field;
        //执行重载
        table.reload('userTable', {
          where: field
        });
      });
      //监听重置
      form.on('submit(reset)', function(data) {
        Object.keys(data.field).forEach(key => (data.field[key] = ''));
        table.reload('userTable', {
          where: data.field
        });
      });
      // 修改user状态
      form.on('switch(enabled)', function (obj) {
        let userId = obj.elem.value;
        let checked = obj.elem.checked ? 'Y' : 'N';
        active.changeUserEnabled(userId,checked);
      });
      // 查询列表接口
      table.render({
          elem: '#userTable'
          ,toolbar: '#toolbar'
          ,height: 'full-110'
          ,url:  ctx + '/sysUser/page'
          ,cellMinWidth: 80
          ,page: true //开启分页
          ,cols: [[ //表头
              {type: 'checkbox', fixed: 'left'},
              {field: 'id', title: 'ID', hide:true},
              {field: 'avatar', title: "头像", templet: function (d) { return crud.showImg(d.avatar); }},
              {field: 'nickName', title: '昵称'},
              {field: 'userName', title: '账户'},
              {field: 'sex', title: "性别", templet: function (d) { return crud.getDictValue('sex',d.sex);}},
              {field: 'phonenumber', title: '手机号'},
              {field: 'enabled', align: "center", templet: '#enabledTpl', title: '状态'},
              {field: 'deptName', title: '部门名称'},
              {field: 'postName', title: '岗位名称'},
              {toolbar: '#tableBar', title: '操作', width: 300, align:'center',fixed: 'right'}
          ]]
      });
      //头工具栏事件
      table.on('toolbar(userTable)', function(obj) {
        let checkStatus = table.checkStatus(obj.config.id)
                ,data = checkStatus.data;
        switch(obj.event){
          case 'export':
            active.exportExcel();
            break;
          case 'add':
            active.addView();
            break;
          case 'removes':
            if (data.length === 0) {
              layer.msg('请选择需要删除的行')
            } else {
              active.removes(data);
            }
            break;
        }
      });
      //监听行工具事件
      table.on('tool(userTable)', function(obj) {
          let data = obj.data //获得当前行数据
              ,layEvent = obj.event;
          if(layEvent === 'edit'){
            active.editView(data.id);
          } else if(layEvent === 'remove'){
            active.remove(data.id);
          } else if(layEvent === 'pass'){
            active.pass(data.id);
          }
      });
      /* 触发弹层 */
      let active = {
        /**
         *  导出excel
         * */
        exportExcel: function() {
          // 打开loading
          let loading = layer.load(0, {
            shade: false,
            time: 2 * 1000
          });
          $(location).attr('href',  ctx + '/sysUser/exportExcel');
          // 关闭loading
          layer.close(loading);
        },
        /**
         * 添加
         * */
        addView: function() {
          layer.open({
            type: 2
            ,shade: 0.3
            ,title: "添加用户"
            ,content: ctx + '/sysUser/addPage'
            ,maxmin: true
            ,scrollbar: false
            ,area: ['100%', '100%']
            ,btn: ['确定', '取消']
            ,yes: function(index, layero){
              let submit = layero.find('iframe').contents().find('#save-submit');
              submit.trigger('click');
            }
          });
        },
        /**
         * 编辑
         * @param id id
         * */
        editView: function(id) {
          layer.open({
            type: 2
            ,shade: 0.3
            ,title: '修改用户'
            ,content: ctx + '/sysUser/editPage/' + id
            ,maxmin: true
            ,scrollbar: false
            ,area: ['100%', '100%']
            ,btn: ['确定', '取消']
            ,yes: function(index, layero){
              let submit = layero.find('iframe').contents().find('#save-submit');
              submit.trigger('click');
            }
          });
        },
        /**
         * 删除单个条目
         * @param id id
         */
        remove: function(id) {
          layer.confirm('真的删除行么', function(index) {
            //向服务端发送删除指令
            $.ajax({
              type: 'DELETE',
              url:  ctx + '/sysUser/remove/' + id,
              contentType:'application/json;charset=UTF-8',
              dataType: 'json',
              success: function(result) {
                layer.msg(result.message);
                if (result.code === 200) {
                  layer.close(index);
                  table.reload('userTable');
                }
              }
            });
          });
        },
        /**
         * 批量删除
         * @param obj 对象
         */
        removes: function(obj) {
          let flag = $.inArray(true, obj.map(x => {return x.userName === 'admin'}));
          if (flag >= 0) {
            layer.msg('禁止删除超级管理员');
            return false;
          }
          let ids = fun.objToArrIds(obj);
          layer.confirm('真的删除行么', function(index) {
            //向服务端发送删除指令
            $.ajax({
              type: 'POST',
              url:  ctx + '/sysUser/removes',
              data: JSON.stringify(ids),
              contentType:'application/json;charset=UTF-8',
              dataType: 'json',
              success: function(result) {
                layer.msg(result.message);
                if (result.code === 200) {
                  layer.close(index);
                  table.reload('userTable');
                }
              }
            });
          });
        },
        /**
         * 修改用户状态
         * @param userId 用户id
         * @param checked 状态
         */
        changeUserEnabled: function (userId,checked) {
          $.ajax({
            type: 'POST',
            url:  ctx + '/sysUser/edit',
            data: JSON.stringify({
              id: userId,
              enabled: checked
            }),
            contentType:'application/json;charset=UTF-8',
            dataType: 'json',
            success: function(result) {
              layer.msg(result.message);
              if (result.code === 200) {
                table.reload('userTable');
              }
            }
          });
        },
        /**
         * 重置密码
         * @param id id
         */
        pass: function (id) {
          layer.confirm('确认重置密码么', function(index) {
            $.ajax({
              type: 'POST',
              url:  ctx + '/sysUser/resetPass',
              data: JSON.stringify({
                id
              }),
              contentType:'application/json;charset=UTF-8',
              dataType: 'json',
              success: function(result) {
                layer.msg(result.message);
                if (result.code === 200) {
                  layer.close(index);
                  table.reload('userTable');
                }
              }
            });
          });
        }
      };
  });
</script>
</body>
</html>
